package cc.co.cutenimy.nimyexplore.model.expression;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cc.co.cutenimy.nimyexplore.model.jdbc.ConnectionInstance;

/**
 * Use Regular to parse expression.
 * 
 * @author 234aini@gmail.com
 * 
 */
public class RegularExpressionMachine implements ExpressionMachine {

	private final ConnectionInstance connectionInstance;

	public RegularExpressionMachine(final ConnectionInstance connectionInstance) {
		this.connectionInstance = connectionInstance;
	}

	private static Pattern VARIABLE_PATTERN = Pattern
			.compile("@\\{[^@\\{\\}]+?\\}");

	/**
	 * A simple implement
	 */
	public String eval(String expression) {
		if (!expression.contains("@")) {
			return expression;
		}
		Matcher matcher = VARIABLE_PATTERN.matcher(expression);
		int start = 0;
		StringBuilder resultBuilder = new StringBuilder(128);
		while (matcher.find()) {
			resultBuilder.append(expression.substring(start, matcher.start()));
			String group = matcher.group();
			resultBuilder.append(evalVariable(group));
			start = matcher.end();
		}
		if (start < expression.length()) {
			resultBuilder.append(expression.substring(start));
		}
		return resultBuilder.toString();
	}

	/**
	 * Eval variable value like @{host}
	 * 
	 * @param variable
	 * @return
	 */
	public String evalVariable(final String variable) {
		Pattern pattern = Pattern.compile("@\\{(.*)\\}");
		Matcher matcher = pattern.matcher(variable);
		if (matcher.find()) {
			String group = matcher.group(1);
			return connectionInstance.getOptionValueByName(group)
					.getStringValue();
		}
		return "TODO";
	}

	public ConnectionInstance getConnectionInstance() {
		return connectionInstance;
	}
}
